package com.trace.service.impl;

import java.util.List;

import com.google.inject.Inject;
import com.trace.dao.BookDao;
import com.trace.dao.BorrowBookDao;
import com.trace.entity.Book;
import com.trace.entity.BorrowBook;
import com.trace.service.BorrowBookManager;

public class BorrowBookManagerImpl implements BorrowBookManager {

	private static final int MAX_BORROW_BOOK_COUNT = 5;

	private BorrowBookDao borrowBookDao;

	private BookDao bookDao;

	@Inject
	public void setBorrowBookDao(BorrowBookDao borrowBookDao) {
		this.borrowBookDao = borrowBookDao;
	}
	
	@Inject
	public void setBookdao(BookDao bookDao) {
		this.bookDao = bookDao;
	}
	
	public boolean borrowBook(String[] bookSelected, int customerId) {
		BorrowBook borrowBook = new BorrowBook();
		Book book = new Book();

		for (int i = 0; i < bookSelected.length; i++) {
			borrowBook.setCustomerId(customerId);
			borrowBook.setBookId(Integer.parseInt(bookSelected[i]));
			if (!borrowBookDao.insertBorrowBook(borrowBook)) {
				return false;
			}

			book.setBookId(Integer.parseInt(bookSelected[i]));
			book = bookDao.findBookByID(book);
			book.setBookCount(book.getBookCount() - 1);
			if (!bookDao.updateBookCount(book)) {
				return false;
			}
		}
		return true;

	}

	public boolean returnBook(String[] borrowSelected, int customerId) {

		BorrowBook borrowBook = new BorrowBook();
		Book book = new Book();

		for (int i = 0; i < borrowSelected.length; i++) {
			borrowBook.setBorrowId(Integer.parseInt(borrowSelected[i]));
			borrowBook = borrowBookDao.findBorrowBookByID(borrowBook);
			if (!borrowBookDao.updateBorrowBook(borrowBook)) {
				return false;
			}

			book.setBookId(borrowBook.getBookId());
			book = bookDao.findBookByID(book);
			book.setBookCount(book.getBookCount() + 1);
			if (!bookDao.updateBookCount(book)) {
				return false;
			}
		}
		return true;

	}

	public List<BorrowBook> searchBorrowBook(BorrowBook paramBorrowBook) {
		List<BorrowBook> borrowBookList = borrowBookDao
				.findBorrowBookByCondition(paramBorrowBook);
		return borrowBookList;
	}

	public int searchBorrowBookCount(BorrowBook paramBorrowBook) {
		int borrowCount = borrowBookDao.countBorrowBook(paramBorrowBook);
		return borrowCount;
	}

	public boolean checkBorrowBookCount(int customerId, int currentbBrrowCount) {
		BorrowBook borrowBook = new BorrowBook();
		borrowBook.setCustomerId(customerId);
		int totalCount = currentbBrrowCount + searchBorrowBookCount(borrowBook);
		if (totalCount > MAX_BORROW_BOOK_COUNT) {
			return false;
		} else {
			return true;
		}
	}

}
